package com.tongfusoft.web.core.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import ognl.Ognl;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.xwork2.ActionContext;
import com.tongfusoft.exception.ObjectConvertException;
import com.tongfusoft.exception.ServiceException;
import com.tongfusoft.utils.BeanUtilsEx;
import com.tongfusoft.utils.JsonUtils;
import com.tongfusoft.utils.Logger;
import com.tongfusoft.utils.UIDGeneratorService;
import com.tongfusoft.utils.web.WebUtils;
import com.tongfusoft.web.core.Constant;
import com.tongfusoft.web.core.data.BaseData;
import com.tongfusoft.web.core.data.User;
import com.tongfusoft.web.utils.DataBeanDetector;

public class ManagementBaseActionAdapter extends ManagementBaseAction{
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(ManagementBaseActionAdapter.class);

	@Override
	public List<BaseData> convertParam2List() {
		//必须使用json格式的提交
		//每个json对象就是一个bd
		//通过datalist参数获取所有的内容
		try {
			Map reqParams = WebUtils.getRequestParameters(getRequest());
			
			User user = (User)super.getSession().getAttribute(Constant.SESSION_USER);
			JSONArray jsonArry = JSONArray.fromObject(super.getParamByName("datalist"));
			List<BaseData> list = new ArrayList<BaseData>();
			
			for(int i=0;i<jsonArry.size();i++){
				BaseData bd = super.getDataDefine((String)reqParams.get("beanName"));
				Map params = JsonUtils.getMap4Json(jsonArry.getJSONObject(i).toString());
				params = this.convertMap(params);
				
				list.add(this.fillDB(params, user, bd));
			}
			
			return list;
			
		} catch (Exception e) {
			throw new ObjectConvertException(e.getMessage());
		}
	}
	
	private BaseData fillDB(Map params,User user,BaseData bd){
		if (this.getOper().equals(Constant.OPER_ADD)) {
			//设置主键,guid
			if(logger.isDebugEnabled()){
				logger.debug(bd.getPkName());
				logger.debug(params.get(bd.getPkName()));
			}
			
			if(StringUtils.isEmpty((String)params.get(bd.getPkName()))){
				params.put(bd.getPkName(), UIDGeneratorService.getUUID());
			}
			
			
			//设置创建人
			if(user != null){
				params.put(BaseData.FIELD_CREATEDBY, user.getPkValue());
				params.put(BaseData.FIELD_LASTUPDBY, user.getPkValue());
			}
		} else {
			//设置更新人
			if(user != null){
				params.put(BaseData.FIELD_LASTUPDBY, user.getPkValue());
			}
			
			//设置主键
			params.put(bd.getPkName(), params.get("id"));
		}
		
		try {
			if(logger.isDebugEnabled()){
				logger.debug("request info:" + params.toString());
			}
			
			BeanUtilsEx.map2Bean(params,bd);
			
			if(logger.isDebugEnabled()){
				logger.debug("convert data info:" + bd.toString());
			}
			
			return bd;
		} catch (Exception e) {
			throw new ServiceException(e);
		} 
		
	}
	
	@Override
	public BaseData convertParam2Obj(){
		Map params = WebUtils.getRequestParameters(getRequest());
		BaseData bd = super.getDataDefine((String)params.get("beanName"));
		User user = (User)super.getSession().getAttribute(Constant.SESSION_USER);
		
		params = this.convertMap(params);
		
		return this.fillDB(params, user, bd);
	}
	
	
	/*private String convertKeyName(String name){
		String[] warpNames = StringUtils.split(name.toLowerCase(),
				"_");
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < warpNames.length; i++) {
			if (i == 0) {
				sb.append(warpNames[i]);
			} else {
				sb.append(warpNames[i].substring(0, 1).toUpperCase()
						+ warpNames[i].substring(1));
			}

		}
		
		return sb.toString();
	}*/
	
	/**
	 * 获取BaseData的定义
	 * @param params
	 * @return
	 
	private BaseData getDataDefine(Map params){
		if(StringUtils.isNotEmpty((String)params.get("beanName"))){
			String className = DataBeanDetector.getDataBeanName((String)params.get("beanName"));
			Logger.debug("bean name:" + className);
			if(StringUtils.isNotEmpty(className)){
				try {
					BaseData bd = (BaseData)Class.forName(className).newInstance();
					
					return bd;
				} catch (Exception e) {
					throw new ServiceException(e);
				}
			}else{
				throw new ServiceException("convert error,not found matching bean:" + className); 
			}
		}else{
			throw new ServiceException("convert error,not found beanName");
		}
	}
	*/

}
